<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Asymptix\HtmlDomParser\HtmlDomParser;
use Illuminate\Support\Facades\Log;
use App\Models\Section;
use App\Models\Operation;
use App\Models\Book;

class updateSectionsByUrlFromQuanShuWu implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	private $url;
	private $order;
	private $book;
	private $cOrder;
	
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($url, $order, $cOrder, Book $book) {
		$this->url = $url;
		$this->order = $order;
		$this->cOrder = $cOrder;
		$this->book = $book;
	}
	
	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		if($this->attempts() >= 5) {
			Log::info('请求超过五次，均失败！');
			Operation::create([
				'action' => '小说更新-队列-章节请求失败',
				'content' => $this->book->name.' => '.$this->order.'/'.$this->cOrder.' => 请求超过五次，均失败！'
			]);
			$this->delete();
			return 0;
		}
		$html = new HtmlDomParser();
		$html->loadUrl($this->url);
		$name = $html->find('h1', 0)->plaintext;
		$ps = $html->find('#content', 0)->find('p');
		$content = '';
		foreach ($ps as $p) {
			$content .= $p->outertext;
		}
		if(!is_null($name) && !is_null($content)) {
			$section = Section::select(['id', 'name'])
					->where('book_id', $this->book->id)
					->where('order', $this->order)
					->first();
			if(is_null($section)) {
				$section = Section::create([
					'book_id' => $this->book->id,
				]);
			}
			if(is_null($section->name)) {
				Log::info('新增！  '.$this->order.'/'.$this->cOrder.'  更新《'.$this->book->name.'》章节：'.$name);
				Operation::create([
					'action' => '新增小说章节',
					'content' => '新增！  '.$this->order.'/'.$this->cOrder.'  更新《'.$this->book->name.'》章节：'.$name
				]);
			}else {
				Log::info($this->order.'/'.$this->cOrder.'  更新《'.$this->book->name.'》章节! '.$section->name.' => '.$name);
				Operation::create([
					'action' => '更新小说章节',
					'content' => $this->order.'/'.$this->cOrder.'  更新《'.$this->book->name.'》章节! '.$section->name.' => '.$name,
				]);
			}
			$data = [
				'name' => $name,
				'content' => $content,
				'order' => $this->order,
			];
			$section->update($data);
			return 1;
		}
		return 0;
	}
}
